﻿using Abp.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using Abp.Extensions;
using Abp.Linq.Extensions;
using System.Threading.Tasks;
using System.Data.Entity;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using MyCompanyName.AbpZeroTemplate.Prm.System.Dto;

namespace MyCompanyName.AbpZeroTemplate.Prm.System
{
    public class SubstanceAppService : AbpZeroTemplateAppServiceBase, ISubstanceAppService
    {
        private readonly SubstanceManager substanceManager;

        public SubstanceAppService(SubstanceManager _substanceManager)
        {
            substanceManager = _substanceManager;
        }

        public async Task<Abp.Application.Services.Dto.PagedResultOutput<Dto.SubstanceOutPut>> GetAll(Dto.GetSubstanceInPut input)
        {
            var query = substanceManager.substanceRepository.GetAll()
                .WhereIf(
                    !input.cas.IsNullOrWhiteSpace(),
                    u => u.CAS.Contains(input.cas)).
                WhereIf(!input.cnName.IsNullOrWhiteSpace(),
                    u => u.CnName.Contains(input.cnName)).
                WhereIf(!input.enName.IsNullOrWhiteSpace(),
                    u => u.EnName.Contains(input.enName));

            var subCount = await query.CountAsync();
            var substances = await query
                .OrderBy(input.Sorting)
                .PageBy(input)
                .ToListAsync();

            var subListDtos = substances.MapTo<List<SubstanceOutPut>>();

            return new PagedResultOutput<SubstanceOutPut>(
                subCount,
                subListDtos
                );
        }

        [Abp.Authorization.AbpAuthorize(MyCompanyName.AbpZeroTemplate.Authorization.AppPermissions.Pages_SystemManager_Substance_Create)]
        public async Task CreateSubstance(CreateSubstanceInput input)
        {
            Substance model = input.MapTo<Substance>();
            await substanceManager.substanceRepository.InsertAsync(model);
        }


        public SubstanceOutPut GetById(int id)
        {
            var substance = substanceManager.substanceRepository.GetAll().Include("Products").Where(x => x.Id == id).SingleOrDefault();
            var outPut = substance.MapTo<SubstanceOutPut>();
            return outPut;
        }


        public async Task SetSubstanceProduct(CreateProductInPut input)
        {
            var substance = new Substance() { Id = input.SubstanceId, Formula = input.Formula, MolecularWeight = input.MolecularWeight, CnName = input.CnName, EnName = input.EnName, CAS = input.CAS };
            var product = new Product() { Id = input.ProductId, Code = input.ProductNo };
            await substanceManager.SetSubstanceProduct(substance, product);
        }
    }
}
